package com.example.app.network

import com.example.app.network.interceptor.LogInterceptor
import com.example.app.network.interceptor.MyHeadInterceptor
import com.google.gson.Gson
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.*
import okhttp3.ResponseBody.Companion.toResponseBody
import okhttp3.internal.http2.ConnectionShutdownException
import org.json.JSONObject
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.io.IOException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeUnit
import kotlin.reflect.jvm.internal.impl.load.kotlin.JvmType

fun <T> createWebService(
        baseUrl: String,
        clazz: Class<T>,
        okHttpClient: OkHttpClient = OkHttpClient.Builder()
            .retryOnConnectionFailure(true)
            //示例：添加公共heads 注意要设置在日志拦截器之前，不然Log中会不显示head信息
            .addInterceptor(MyHeadInterceptor())
            .addInterceptor(LogInterceptor())
            .addInterceptor(object : Interceptor {
                override fun intercept(chain: Interceptor.Chain): Response {
                    var request = chain.request()
                    try {
                        var response = chain.proceed(request)
                        var bodyString = response.body!!.string()

                        if (bodyString != null && !bodyString.isEmpty()) {
                            var json = JSONObject(bodyString)
                            var code = json.getString("code").toInt()
                            if (code > 0) {
                                throw Exception(json.getString("msg").toString())
                            } else {
                                var contentType = response.body?.contentType()
                                var bodyStr = bodyString
                                    .toResponseBody(contentType)
                                var result = response.newBuilder()
                                    .body(bodyStr)
                                    .build()
                                return result
                            }
                        } else {
                            var contentType = response.body?.contentType()
                            var bodyStr = bodyString
                                .toResponseBody(contentType)
                            var result = response.newBuilder()
                                .body(bodyStr)
                                .build()
                            return result
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        var msg = ""
                        when (e) {
                            is SocketTimeoutException -> {
                                msg = "请求超时"
                            }

                            is UnknownHostException -> {
                                msg = "无网络"
                            }

                            is ConnectionShutdownException -> {
                                msg = "网络断开"
                            }

                            is IOException -> {
                                msg = "服务器错误"
                            }

                            is IllegalStateException -> {
                                msg = "${e.message}"
                            }

                            else -> {
                                msg = "${e.message}"
                            }
                        }

                        return Response.Builder()
                            .request(request)
                            .protocol(Protocol.HTTP_1_1)
                            .code(999)
                            .message(msg)
                            .body(
                                "{${e}}"
                                    .toResponseBody(null)
                            ).build()
                    }
                }
            })
            .connectTimeout(
                100,
                TimeUnit.SECONDS
            )
            .writeTimeout(
                100,
                TimeUnit.SECONDS
            )
            .readTimeout(
                100,
                TimeUnit.SECONDS
            )
            .build(),
): T {
    val moshi = Moshi.Builder() // adapter
        .add(KotlinJsonAdapterFactory())
        .build()


    return Retrofit.Builder()
        .baseUrl(baseUrl)
        .client(okHttpClient)
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .build()
        .create(clazz)
}


